<template>
  <div class="inventory-management">
    <!-- 左侧实验室列表 -->
    <div class="lab-list">
      <div class="list-header">
        <h3>实验室列表</h3>
        <div class="header-buttons">
          <button 
            class="add-lab-btn" 
            @click="createLab"
            title="新建实验室"
            v-if="isAdmin"
          >
            <span>+</span>
          </button>
        </div>
      </div>
      <div class="list-content">
        <LabList 
          @select="handleLabSelect"
          @edit="handleLabEdit"
          @delete="handleLabDelete"
          @add-user="handleAddUserToLab"
          @download="handleLabDownload"
        />
      </div>
    </div>

    <!-- 右侧库存表格 -->
    <div class="inventory-list">
      <div class="inventory-header">
        <div class="header-content">
          <div class="header-left">
            <h3>{{ labStore.selectedLab ? `${labStore.selectedLab.name} - 库存明细` : '请选择实验室' }}</h3>
            <span v-if="inventoryStore.total > 0" class="total-count">
              共 {{ inventoryStore.total }} 条记录
            </span>
          </div>
          <div class="header-buttons" v-if="labStore.selectedLab">
            <!-- 搜索框 -->
            <div class="search-container">
              <input
                type="text"
                v-model="searchName"
                @input="handleSearchInput($event)"
                placeholder="按名称搜索..."
                class="search-input"
              />
              <i class="fa fa-search search-icon"></i>
            </div>
            <button 
              v-if="isAdmin || isAdvancedLibraryAdmin || isEditRole ||isAssignRole"
              class="add-item-btn"
              @click="openAddItemModal"
            >
              <span>+</span> 新增库存项
            </button>
            <button 
              v-if="isAdmin || isAdvancedLibraryAdmin || isEditRole ||isAssignRole"
              class="init-inventory-btn"
              @click="openInitInventoryModal"
            >
              <i class="fa fa-upload"></i> 初始化库存
            </button>
            <button 
              v-if="isAdmin || isAdvancedLibraryAdmin || isEditRole ||isAssignRole"
              class="warning-config-btn"
              @click="openWarningConfigModal"
              title="设置库存数量下限预警"
            >
              <i class="fa fa-bell"></i> 设置预警值
            </button>
            <!-- 添加重置筛选按钮 -->
            <button 
              class="reset-filters-btn"
              @click="resetAllFilters"
              title="重置所有筛选条件"
            >
              <i class="fa fa-refresh"></i> 重置筛选
            </button>
          </div>
        </div>
      </div>
      <div class="inventory-content" style="max-height: calc(19 * 40px); overflow-y: auto;">
        <template v-if="labStore.selectedLab">
          <div 
            class="table-container"
            @scroll="handleScroll"
          >
            <table>
              <thead>
                <tr>
                  <th class="column-id">序号</th>
                  <!-- 类型列 -->
                  <th>
                    <div class="column-header">
                      <span>类型</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('type')" :class="{'active': selectedType !== -1}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'type'" class="filter-dropdown" ref="typeFilterDropdown">
                      <div class="type-options">
                        <div class="type-option" @click="selectType(-1)" :class="{'selected': selectedType === -1}">
                          <span>全部</span>
                        </div>
                        <div class="type-option" @click="selectType(InventoryItemType.CHEMICAL)" :class="{'selected': selectedType === InventoryItemType.CHEMICAL}">
                          <span>化学试剂</span>
                        </div>
                        <div class="type-option" @click="selectType(InventoryItemType.ELECTRONIC)" :class="{'selected': selectedType === InventoryItemType.ELECTRONIC}">
                          <span>电子元器件</span>
                        </div>
                        <div class="type-option" @click="selectType(InventoryItemType.OTHER)" :class="{'selected': selectedType === InventoryItemType.OTHER}">
                          <span>其他</span>
                        </div>
                      </div>
                      <div class="filter-actions">
                        <button @click="applyFilter('type')">应用</button>
                        <button @click="cancelFilter('type')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- CAS编号列 -->
                  <th>
                    <div class="column-header">
                      <span>CAS编号</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('casNo')" :class="{'active': searchFilters.casNo}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'casNo'" class="filter-dropdown" ref="casNoFilterDropdown">
                      <input type="text" v-model="searchFilters.casNo" placeholder="搜索CAS编号...">
                      <div class="filter-actions">
                        <button @click="applyFilter('casNo')">应用</button>
                        <button @click="cancelFilter('casNo')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- 名称列 -->
                  <th>
                    <div class="column-header">
                      <span>名称</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('name')" :class="{'active': searchFilters.name}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'name'" class="filter-dropdown" ref="nameFilterDropdown">
                      <input type="text" v-model="searchFilters.name" placeholder="搜索名称...">
                      <div class="filter-actions">
                        <button @click="applyFilter('name')">应用</button>
                        <button @click="cancelFilter('name')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- 纯度列 -->
                  <th>
                    <div class="column-header">
                      <span>型号/纯度</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('purity')" :class="{'active': searchFilters.purity}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'purity'" class="filter-dropdown" ref="purityFilterDropdown">
                      <input type="text" v-model="searchFilters.purity" placeholder="搜索纯度...">
                      <div class="filter-actions">
                        <button @click="applyFilter('purity')">应用</button>
                        <button @click="cancelFilter('purity')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- 品牌列 -->
                  <th>
                    <div class="column-header">
                      <span>品牌</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('brand')" :class="{'active': searchFilters.brand}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'brand'" class="filter-dropdown" ref="brandFilterDropdown">
                      <input type="text" v-model="searchFilters.brand" placeholder="搜索品牌...">
                      <div class="filter-actions">
                        <button @click="applyFilter('brand')">应用</button>
                        <button @click="cancelFilter('brand')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- 货号列 -->
                  <th>
                    <div class="column-header">
                      <span>货号</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('catalogNumber')" :class="{'active': searchFilters.catalogNumber}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'catalogNumber'" class="filter-dropdown" ref="catalogNumberFilterDropdown">
                      <input type="text" v-model="searchFilters.catalogNumber" placeholder="搜索货号...">
                      <div class="filter-actions">
                        <button @click="applyFilter('catalogNumber')">应用</button>
                        <button @click="cancelFilter('catalogNumber')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- 规格列 -->
                  <!-- <th>
                    <div class="column-header">
                      <span>规格</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('specs')" :class="{'active': searchFilters.specs}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'specs'" class="filter-dropdown" ref="specsFilterDropdown">
                      <input type="text" v-model="searchFilters.specs" placeholder="搜索规格...">
                      <div class="filter-actions">
                        <button @click="applyFilter('specs')">应用</button>
                        <button @click="cancelFilter('specs')">取消</button>
                      </div>
                    </div>
                  </th> -->
                  
                  

                  <!-- 库存单位列 -->
                  <th>
                    <div class="column-header">
                      <span>库存单位</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('unit')" :class="{'active': searchFilters.unit}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'unit'" class="filter-dropdown" ref="unitFilterDropdown">
                      <input type="text" v-model="searchFilters.unit" placeholder="搜索库存单位...">
                      <div class="filter-actions">
                        <button @click="applyFilter('unit')">应用</button>
                        <button @click="cancelFilter('unit')">取消</button>
                      </div>
                    </div>
                  </th>

                  <!-- 库存数量列 -->
                  <th>
                    <div class="column-header">
                      <span>库存数量</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('stockNum')" :class="{'active': searchFilters.stockNum}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'stockNum'" class="filter-dropdown" ref="stockNumFilterDropdown">
                      <input type="text" v-model="searchFilters.stockNum" placeholder="搜索库存数量...">
                      <div class="filter-actions">
                        <button @click="applyFilter('stockNum')">应用</button>
                        <button @click="cancelFilter('stockNum')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- 存储地点列 -->
                  <th>
                    <div class="column-header">
                      <span>存储地点</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('location')" :class="{'active': searchFilters.location}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'location'" class="filter-dropdown" ref="locationFilterDropdown">
                      <input type="text" v-model="searchFilters.location" placeholder="搜索存储地点...">
                      <div class="filter-actions">
                        <button @click="applyFilter('location')">应用</button>
                        <button @click="cancelFilter('location')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- 到期时间列 -->
                  <th>
                    <div class="column-header">
                      <span>到期时间</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('expirationDate')" :class="{'active': searchFilters.expirationDate}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'expirationDate'" class="filter-dropdown" ref="expirationDateFilterDropdown">
                      <input type="date" v-model="searchFilters.expirationDate" placeholder="选择日期...">
                      <div class="filter-actions">
                        <button @click="applyFilter('expirationDate')">应用</button>
                        <button @click="cancelFilter('expirationDate')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- 课题组列 -->
                  <th>
                    <div class="column-header">
                      <span>课题组</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('subject')" :class="{'active': searchFilters.subject}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'subject'" class="filter-dropdown" ref="subjectFilterDropdown">
                      <input type="text" v-model="searchFilters.subject" placeholder="搜索课题组...">
                      <div class="filter-actions">
                        <button @click="applyFilter('subject')">应用</button>
                        <button @click="cancelFilter('subject')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- 创建者列 -->
                  <th>
                    <div class="column-header">
                      <span>创建者</span>
                      <div class="header-filter">
                        <i class="fa fa-filter" @click="toggleFilter('creatorName')" :class="{'active': searchFilters.creatorName}"></i>
                      </div>
                    </div>
                    <div v-if="activeFilter === 'creatorName'" class="filter-dropdown" ref="creatorNameFilterDropdown">
                      <input type="text" v-model="searchFilters.creatorName" placeholder="搜索创建者...">
                      <div class="filter-actions">
                        <button @click="applyFilter('creatorName')">应用</button>
                        <button @click="cancelFilter('creatorName')">取消</button>
                      </div>
                    </div>
                  </th>
                  
                  <!-- 入库时间 -->
                  <th>
                    <div class="column-header">
                      <span>入库时间</span>
                      
                    </div>
                    
                  </th>

                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in inventoryStore.inventoryItems" :key="item.id">
                  <td class="column-id">{{ item.id }}</td>
                  <td>{{ getItemTypeName(item.type) }}</td>
                  <td>{{ item.casNo || '-' }}</td>
                  <td>{{ item.name }}</td>
                  <td>{{ item.purity || '-' }}</td>
                  <td>{{ item.brand || '-' }}</td>
                  <td>{{ item.catalogNumber || '-' }}</td>
                  <!-- <td>{{ item.specs || '-' }}</td> -->
                  <td>{{ item.unit }}</td>
                  <td>{{ item.stockNum }}</td>
                  <td>{{ item.location || '-' }}</td>
                  <td>{{ item.expirationDate }}</td>
                  <td>{{ item.subject }}</td>
                  <td>{{ item.creatorName }}</td>
                  <td>{{ item.warehousingTime }}</td>
                  <td>
                    <div class="action-buttons">
                      <button 
                        v-if="(isAdmin || isAdvancedLibraryAdmin || isEditRole || isoutboundRole ||isAssignRole)"
                        class="update-btn" 
                        @click="handleUpdateInventory(item)"
                      >
                        更新库存
                      </button>
                      <button 
                        v-if="(isAdmin || isAdvancedLibraryAdmin ||isAssignRole)"
                        class="delete-btn" 
                        @click="handleDeleteInventoryItem(item)"
                      >
                        删除
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
            
            <!-- 加载状态 -->
            <div v-if="inventoryStore.loadingMore" class="loading-more">
              加载中...
            </div>
            
            
            
            <!-- 空状态提示 -->
            <div v-if="inventoryStore.inventoryItems.length === 0 && !inventoryStore.isLoading" class="empty-folder">
              该实验室暂无库存物品
            </div>
          </div>
        </template>
        <div v-else class="empty-state">
          请先选择左侧实验室
        </div>
      </div>
    </div>
  </div>

  <!-- 创建实验室模态框 -->
  <CreateLabModal
    :show="showCreateLabModal"
    @close="showCreateLabModal = false"
    @create="handleCreateLab"
  />

  <!-- 编辑实验室模态框 -->
  <EditLabModal
    :show="showEditLabModal"
    :lab="labToEdit"
    @close="showEditLabModal = false"
    @update="handleUpdateLab"
  />

  <!-- 新增库存项模态框 -->
  <AddInventoryItemModal
    :show="showAddItemModal"
    :lab-id="labStore.selectedLab?.id || ''"
    @close="showAddItemModal = false"
    @submit="handleAddItem"
  />

  <!-- 添加用户到实验室模态框 -->
  <AddUserToLabModal
    :show="showAddUserModal"
    :lab-id="selectedLabForUser?.id || ''"
    @close="showAddUserModal = false"
    @user-added="handleUserAdded"
  />

  <!-- 初始化库存模态框 -->
  <InitInventoryModal
    :show="showInitInventoryModal"
    :lab-id="labStore.selectedLab?.id || ''"
    @close="showInitInventoryModal = false"
    @init-success="handleInitInventorySuccess"
  />

  <!-- 更新库存模态框 -->
      <UpdateInventoryModal
        v-if="selectedItem"
        :show="showUpdateInventoryModal"
        :item="selectedItem"
        @close="closeUpdateInventoryModal"
        @update-success="handleUpdateInventorySuccess"
      />

      <!-- 预警设置模态框 -->
      <WarningConfigModal
        :show="showWarningConfigModal"
        :lab-id="labStore.selectedLab?.id || ''"
        @close="showWarningConfigModal = false"
        @update-success="handleWarningConfigSuccess"
      />
      
      <!-- 下载库存数据模态框 -->
      <DownloadInventoryModal
        :show="showDownloadModal"
        :lab-id="selectedLabForDownload?.id || ''"
        @close="showDownloadModal = false"
      />
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick, watch } from 'vue';
import type { User } from '../types';
import WarningConfigModal from '../components/LabAndInventory/WarningConfigModal.vue';
import DownloadInventoryModal from '../components/LabAndInventory/DownloadInventoryModal.vue';
import LabList from '../components/LabAndInventory/LabList.vue';
import CreateLabModal from '../components/LabAndInventory/CreateLabModal.vue';
import EditLabModal from '../components/LabAndInventory/EditLabModal.vue';
import AddInventoryItemModal from '../components/LabAndInventory/AddInventoryItemModal.vue';
import { ToastService } from '../utils/toastService';
import AddUserToLabModal from '../components/LabAndInventory/AddUserToLabModal.vue';
import InitInventoryModal from '../components/LabAndInventory/InitInventoryModal.vue';
import UpdateInventoryModal from '../components/LabAndInventory/UpdateInventoryModal.vue';
import { useLabStore, type Lab, type CreateLabRequest } from '../stores/labStore';
import { useInventoryStore } from '../stores/inventoryStore';
import { getItemTypeName, type InventoryItem, type CreateInventoryItemRequest, InventoryItemType } from '../types/inventory';
// 导入ComponentPublicInstance类型
import type { ComponentPublicInstance } from 'vue';

const showAddItemModal = ref(false);
const showCreateLabModal = ref(false);
const showAddUserModal = ref(false);
const showInitInventoryModal = ref(false);
const showUpdateInventoryModal = ref(false);
const showWarningConfigModal = ref(false);
const showDownloadModal = ref(false);
const selectedLabForUser = ref<Lab | null>(null);
const selectedLabForDownload = ref<Lab | null>(null);
const selectedItem = ref<InventoryItem | null>(null);
const labStore = useLabStore();
const inventoryStore = useInventoryStore();

// 获取当前登录用户信息
const userInfoStr = localStorage.getItem('userInfo');
const currentUser = ref<User | null>(userInfoStr ? JSON.parse(userInfoStr) : null);
const isAdmin = computed(() => currentUser.value?.roleName === '超级管理员');
const isAdvancedLibraryAdmin = computed(() => {
  if (isAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !labStore.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === labStore.selectedLab?.id && roleId === 4
  );
});
const isoutboundRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !labStore.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === labStore.selectedLab?.id && roleId === 9
  );
});
const isEditRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !labStore.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === labStore.selectedLab?.id && roleId === 10
  );
});

const isAssignRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !labStore.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === labStore.selectedLab?.id && roleId === 12
  );
});

// 本地UI状态，-1 表示显示所有类型
const selectedType = ref<number>(-1); 
// 搜索关键词
const searchName = ref<string>('');

// 搜索条件状态
const searchFilters = ref({
  casNo: '',
  name: searchName.value, // 整合现有的搜索功能
  purity: '',
  brand: '',
  catalogNumber: '',
  specs: '',
  unit: '',
  stockNum: '',
  location: '',
  expirationDate: '',
  subject: '',
  creatorName: '',
  createTime: '',
});

// 当前激活的筛选器
const activeFilter = ref<string | null>(null);


// 定义筛选器下拉框的引用类型
type FilterDropdownRef = ComponentPublicInstance | null;

// 存储所有筛选下拉框的引用
const filterDropdowns = {
  type: ref<FilterDropdownRef>(null),
  casNo: ref<FilterDropdownRef>(null),
  name: ref<FilterDropdownRef>(null),
  purity: ref<FilterDropdownRef>(null),
  brand: ref<FilterDropdownRef>(null),
  catalogNumber: ref<FilterDropdownRef>(null),
  specs: ref<FilterDropdownRef>(null),
  unit: ref<FilterDropdownRef>(null),
  stockNum: ref<FilterDropdownRef>(null),
  location: ref<FilterDropdownRef>(null),
  expirationDate: ref<FilterDropdownRef>(null),
  subject: ref<FilterDropdownRef>(null),
  creatorName: ref<FilterDropdownRef>(null),
  createTime: ref<FilterDropdownRef>(null),
} as const;

// 存储筛选图标元素的引用
const filterIcons = ref<{
  [K in FilterField]?: Element;
}>({});

// 定义筛选字段的类型
type FilterField = keyof typeof filterDropdowns;

// 切换筛选器显示状态
const toggleFilter = (fieldName: FilterField) => {
  // 如果点击的是当前已激活的筛选器，则关闭它
  if (activeFilter.value === fieldName) {
    activeFilter.value = null;
    return;
  }
  
  // 先关闭其他筛选器
  activeFilter.value = null;
  
  // 然后激活当前筛选器
  nextTick(() => {
    activeFilter.value = fieldName;
    
    // 获取筛选图标元素
    const filterIcon = filterIcons.value[fieldName] as HTMLElement | null;

    if (filterIcon && filterDropdowns[fieldName].value) {
      // 获取筛选图标位置
      const iconRect = filterIcon.getBoundingClientRect();
      const tableContainer = document.querySelector('.table-container') as HTMLElement;
      const tableElement = document.querySelector('.table-container table') as HTMLElement;
      const tableRect = tableElement.getBoundingClientRect();
      
      // 获取表格容器的滚动位置
      const scrollLeft = tableContainer.scrollLeft;
      
      // 获取下拉框元素
      const dropdown = filterDropdowns[fieldName].value.$el;
      
      // 设置下拉框位置
      dropdown.style.position = 'fixed';
      dropdown.style.left = `${iconRect.left - tableRect.left + scrollLeft}px`;
      dropdown.style.top = `${iconRect.bottom + window.scrollY + 4}px`;
      dropdown.style.zIndex = '100';
    }
  });
};

// 应用筛选
const applyFilter = async (fieldName: FilterField) => {
  activeFilter.value = null;
  if (labStore.selectedLab) {
    // 如果是类型筛选，记录日志
    if (fieldName === 'type') {
      console.log(`应用类型筛选: ${selectedType.value === -1 ? '全部' : getItemTypeName(selectedType.value)}`);
    }
    await fetchInventoryWithFilters();
  }
};

// 取消筛选
const cancelFilter = (fieldName: FilterField) => {
  // 恢复筛选条件到之前的状态
  if (fieldName === 'type') {
    // 类型筛选器恢复到之前的选择
    // 这里不需要做任何事情，因为selectedType已经在点击选项时更新了
  } else {
    // 其他筛选器恢复到之前的值
    // 这里也不需要做任何事情，因为v-model已经绑定了值
  }
  
  // 关闭筛选下拉框
  activeFilter.value = null;
};

// // 清除筛选
// const clearFilter = async (fieldName: FilterField) => {
//   searchFilters.value[fieldName as keyof typeof searchFilters.value] = '';
//   if (labStore.selectedLab) {
//     await fetchInventoryWithFilters();
//   }
// };

// 重置所有筛选
const resetAllFilters = async () => {
  Object.keys(searchFilters.value).forEach(key => {
    searchFilters.value[key as keyof typeof searchFilters.value] = '';
  });
  selectedType.value = -1;
  if (labStore.selectedLab) {
    await fetchInventoryWithFilters();
  }
};

// 使用所有筛选条件获取库存数据
const fetchInventoryWithFilters = async () => {
  if (!labStore.selectedLab) return;
  
  // 更新searchName以保持兼容性
  searchName.value = searchFilters.value.name;
  
  // 调用库存获取方法
  await inventoryStore.fetchInventoryItems(
    labStore.selectedLab.id,
    true,
    selectedType.value,
    searchFilters.value.name,
    searchFilters.value
  );
};

// 选择类型
const selectType = (type: number) => {
  selectedType.value = type;
};

// // 清除类型筛选
// const clearTypeFilter = async () => {
//   selectedType.value = -1;
//   if (labStore.selectedLab) {
//     await fetchInventoryWithFilters();
//   }
// };

// // 处理类型变化 (保留以兼容其他可能的调用)
// const handleTypeChange = async () => {
//   if (labStore.selectedLab) {
//     await fetchInventoryWithFilters();
//   }
// };

// 处理搜索输入
const handleSearchInput = async (event: Event) => {
  if (labStore.selectedLab) {
    const inputElement = event.target as HTMLInputElement;
    const searchValue = inputElement.value;
    // 确保 searchName 和 searchFilters.name 保持同步
    searchName.value = searchValue;
    searchFilters.value.name = searchValue;
    await fetchInventoryWithFilters();
  }
};

// 组件挂载时，确保inventoryStore.selectedType初始化为-1（全部）
onMounted(() => {
  // 正确设置ref的值
  inventoryStore.selectedType = -1;
  
  // 为筛选图标添加数据属性以便识别
  document.querySelectorAll('.header-filter i').forEach((icon, index) => {
    const fieldNames = ['type', 'casNo', 'name', 'purity', 'brand', 'catalogNumber', 'specs', 'unit', 'stockNum', 'location', 'expirationDate', 'subject', 'creatorName'] as const;
    const fieldName = fieldNames[index];
    if (fieldName) {
      icon.setAttribute('data-field', fieldName);
      filterIcons.value[fieldName] = icon;
    }
  });
});

// 节流函数
function throttle<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: ReturnType<typeof setTimeout> | null = null;
  let previous = 0;

  return function(this: any, ...args: Parameters<T>) {
    const now = Date.now();
    const remaining = wait - (now - previous);
    
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      previous = now;
      func.apply(this, args);
    } else if (!timeout) {
      timeout = setTimeout(() => {
        previous = Date.now();
        timeout = null;
        func.apply(this, args);
      }, remaining);
    }
  };
}

// 处理滚动加载
const handleScroll = throttle((event: Event) => {
  const target = event.target as HTMLElement;
  const { scrollTop, scrollHeight, clientHeight } = target;
  
  // 当滚动到距离底部50px时触发加载更多
  if (scrollHeight - scrollTop - clientHeight < 50 && 
      !inventoryStore.loadingMore && 
      inventoryStore.hasMore) {
    console.log('Loading more items...'); // 添加日志以便调试
    inventoryStore.loadMoreInventoryItems(searchFilters.value);
  }
}, 200);

// 打开新增库存项模态框
const openAddItemModal = () => {
  if (!labStore.selectedLab) {
    ToastService.warning('请先选择一个实验室');
    return;
  }
  showAddItemModal.value = true;
};

// 打开初始化库存模态框
const openInitInventoryModal = () => {
  if (!labStore.selectedLab) {
    ToastService.warning('请先选择一个实验室');
    return;
  }
  showInitInventoryModal.value = true;
};

// 处理初始化库存成功
const handleInitInventorySuccess = () => {
  ToastService.success('库存初始化成功');
};

// 打开预警设置模态框
const openWarningConfigModal = () => {
  if (!labStore.selectedLab) {
    ToastService.warning('请先选择一个实验室');
    return;
  }
  showWarningConfigModal.value = true;
};

// 处理预警设置成功
const handleWarningConfigSuccess = () => {
  ToastService.success('库存预警值设置成功');
};

// 处理实验室下载
const handleLabDownload = (lab: Lab) => {
  if (!lab || !lab.id) {
    ToastService.error('实验室ID不能为空');
    return;
  }
  
  // 设置要下载的实验室ID并打开下载模态框
  selectedLabForDownload.value = lab;
  showDownloadModal.value = true;
};

// 处理新增库存项
const handleAddItem = async (data: CreateInventoryItemRequest) => {
  if (!labStore.selectedLab) return;
  
  const result = await inventoryStore.addInventoryItem(data);
  
  if (result.success) {
    showAddItemModal.value = false;
    ToastService.success('新增库存项成功');
  } else {
    ToastService.error(`新增失败: ${result.message || '未知错误'}`);
  }
};

// 组件挂载时加载实验室列表
onMounted(async () => {
  await labStore.fetchLabs();
  
  // 初始化搜索状态
  searchName.value = '';
  
  // 获取用户信息中的researchGroupId
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    const { researchGroupId } = JSON.parse(userInfo);
    if (researchGroupId) {
      // 查找匹配的实验室
      const matchedLab = labStore.labs.find(lab => lab.id === researchGroupId);
      if (matchedLab) {
        // 自动选择实验室并加载库存
        labStore.selectLab(matchedLab);
        inventoryStore.setSelectedLabId(matchedLab.id);
        await inventoryStore.fetchInventoryItems(matchedLab.id, true, selectedType.value, searchName.value);
      }
    }
  }
});

// 打开创建实验室模态框
const createLab = () => {
  showCreateLabModal.value = true;
};

// 处理创建实验室
const handleCreateLab = async (data: CreateLabRequest) => {
  const success = await labStore.createLab(data);
  if (success) {
    showCreateLabModal.value = false;
    // 如果创建成功，可以选择第一个实验室
    if (labStore.labs.length > 0 && !labStore.selectedLab) {
      labStore.selectLab(labStore.labs[0]);
      // 加载新创建实验室的库存数据
      await inventoryStore.fetchInventoryItems(labStore.labs[0].id, true);
    }
  } else {
    ToastService.error('创建实验室失败，请重试');
  }
};

// 处理实验室选择
const handleLabSelect = async (lab: Lab) => {
  // 重置搜索和筛选条件
  searchName.value = '';
  selectedType.value = -1;
  
  labStore.selectLab(lab);
  inventoryStore.setSelectedLabId(lab.id);
  // 加载选中实验室的库存数据，使用重置后的搜索和筛选条件
  await inventoryStore.fetchInventoryItems(lab.id, true, selectedType.value, searchName.value);
};

// 编辑实验室相关变量
const showEditLabModal = ref(false);
const labToEdit = ref<Lab | null>(null);

// 处理实验室编辑
const handleLabEdit = (lab: Lab) => {
  labToEdit.value = { ...lab };
  showEditLabModal.value = true;
};

// 提交编辑实验室
const handleUpdateLab = async (lab: Lab) => {
  const success = await labStore.updateLab(lab);
  if (success) {
    showEditLabModal.value = false;
    labToEdit.value = null;
  } else {
    ToastService.error('更新实验室失败，请重试');
  }
};

// 处理实验室删除
const handleLabDelete = async (lab: Lab) => {
  if (confirm(`确定要删除实验室"${lab.name}"吗？此操作不可恢复。`)) {
    const success = await labStore.deleteLab(lab.id);
    if (!success) {
      ToastService.error('删除实验室失败，请重试');
    }
  }
};

// 处理添加用户到实验室
const handleAddUserToLab = (lab: Lab) => {
  selectedLabForUser.value = lab;
  showAddUserModal.value = true;
};

// 处理用户添加成功
const handleUserAdded = () => {
  ToastService.success('用户添加成功');
  // 可以在这里刷新实验室列表或执行其他操作
};

// 处理更新库存按钮点击
const handleUpdateInventory = (item: InventoryItem) => {
  selectedItem.value = item;
  showUpdateInventoryModal.value = true;
};

// 关闭更新库存模态框
const closeUpdateInventoryModal = () => {
  showUpdateInventoryModal.value = false;
  selectedItem.value = null;
};

// 处理更新库存成功
const handleUpdateInventorySuccess = () => {
  if (labStore.selectedLab) {
    closeUpdateInventoryModal();
    ToastService.success('库存更新成功');
    // 刷新库存数据
    inventoryStore.fetchInventoryItems(labStore.selectedLab.id, true, inventoryStore.selectedType);
  }
};

// 处理库存项删除
const handleDeleteInventoryItem = async (item: InventoryItem) => {
  if (!confirm(`确定要删除物品"${item.name}"吗？此操作不可恢复。`)) {
    return;
  }

  const result = await inventoryStore.deleteInventoryItem(item);
  
  if (result.success) {
    ToastService.success('删除成功');
  } else {
    ToastService.error(`删除失败: ${result.message || '未知错误'}`);
  }
};

// 监听activeFilter变化，当筛选器关闭时，重置下拉框位置
watch(activeFilter, (newVal, oldVal) => {
  if (!newVal && oldVal) {
    // 关闭筛选器时，重置下拉框样式
    const dropdown = filterDropdowns[oldVal as FilterField].value?.$el;
    if (dropdown) {
      dropdown.style.position = '';
      dropdown.style.left = '';
      dropdown.style.top = '';
      dropdown.style.zIndex = '';
    }
  }
});

</script>

<style scoped>
.inventory-management {
  display: flex;
  height: calc(100vh - 40px); /* 减去padding的高度 */
  gap: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  overflow: hidden; /* 防止页面出现滚动条 */
}

.lab-list {
  flex: 0 0 300px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  max-height: 100%; /* 限制最大高度 */
}

.inventory-list {
  flex: 1;
  min-width: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.total-count {
  color: #666;
  font-size: 14px;
  background-color: #f5f5f5;
  padding: 4px 8px;
  border-radius: 4px;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-container label {
  color: #666;
  font-size: 14px;
}

.type-filter {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  background-color: white;
  cursor: pointer;
  transition: all 0.3s;
}

.type-filter:hover {
  border-color: #40a9ff;
}

.type-filter:focus {
  outline: none;
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.inventory-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-container {
  flex: 1;
  overflow: auto;
  position: relative;
  height: calc(100vh - 180px); /* 限制最大高度，减去header和其他元素的高度 */
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
}

table {
  width: 100%;
  min-width: 1200px;
  border-collapse: collapse;
}

thead {
  position: sticky;
  top: 0;
  background: white;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
  white-space: nowrap;
}

tbody tr:hover {
  background-color: #f5f5f5;
}

.loading-more,
.no-more {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(249, 249, 249, 0.9);
  padding: 12px;
  text-align: center;
  backdrop-filter: blur(4px);
}

/* 滚动条样式 */
.table-container::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.table-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.table-container::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.table-container::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 列表头部样式 */
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.list-header .header-buttons {
  display: flex;
  align-items: center;
}

.add-lab-btn {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #1890ff;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 18px;
  line-height: 1;
}

.add-lab-btn:hover {
  background-color: #40a9ff;
}

.download-btn {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #52c41a;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  line-height: 1;
  margin-right: 8px;
}

.download-btn:hover {
  background-color: #73d13d;
}

.list-content {
  flex: 1;
  overflow: hidden;
}

/* 库存列表头部样式 */
.inventory-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 搜索框样式 */
.search-container {
  position: relative;
  margin-right: 8px;
}

.search-input {
  width: 200px;
  padding: 8px 12px;
  padding-left: 32px; /* 为搜索图标留出空间 */
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.search-input:hover {
  border-color: #40a9ff;
}

.search-input:focus {
  outline: none;
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.search-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  pointer-events: none;
}

.add-item-btn, .init-inventory-btn {
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

.add-item-btn {
  background-color: #1890ff;
  color: white;
  border: none;
}

.add-item-btn:hover {
  background-color: #40a9ff;
}

.init-inventory-btn {
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #d9d9d9;
}

.init-inventory-btn:hover {
  background-color: #e6e6e6;
}

.warning-config-btn {
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #d9d9d9;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s;
}

.warning-config-btn:hover {
  background-color: #fff3e0;
  color: #fa8c16;
  border-color: #fa8c16;
}

.warning-config-btn i {
  font-size: 14px;
}

.reset-filters-btn {
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #d9d9d9;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s;
}

.reset-filters-btn:hover {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #1890ff;
}

.reset-filters-btn i {
  font-size: 14px;
}

.column-header {
  display: flex;
  justify-content: space-between; /* 改回space-between，确保文字和图标分开 */
  align-items: center;
  position: relative;
  width: 100%; /* 确保占满整个th宽度 */
}

/* 确保列标题文字不会与筛选图标重叠 */
.column-header span {
  flex: 1; /* 让文字占据剩余空间 */
  overflow: hidden;
  text-overflow: ellipsis; /* 文字过长时显示省略号 */
  white-space: nowrap;
}

.filter-dropdown {
  position: absolute;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 8px;
  min-width: 200px;
  margin-top: 4px;
  
}

.filter-dropdown input {
  width: 100%;
  padding: 6px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.filter-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
}

.filter-actions button {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  background-color: #f0f0f0;
  border: 1px solid #d9d9d9;
  transition: all 0.3s;
}

.filter-actions button:first-child {
  background-color: #1890ff;
  color: white;
  border: none;
}

.filter-actions button:first-child:hover {
  background-color: #40a9ff;
}

.filter-actions button:last-child:hover {
  background-color: #e6e6e6;
}

.header-filter i {
  cursor: pointer;
  color: #999;
  font-size: 14px;
  transition: color 0.3s;
}

.header-filter i:hover,
.header-filter i.active {
  color: #1890ff;
}

/* 空状态样式 */
.empty-state, .empty-folder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 14px;
  text-align: center;
  padding: 20px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
}

.update-btn, .delete-btn {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.update-btn {
  background-color: #1890ff;
  color: white;
  border: none;
}

.update-btn:hover {
  background-color: #40a9ff;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
  border: none;
}

.delete-btn:hover {
  background-color: #ff7875;
}

/* 列宽控制 */
.column-id {
  width: 80px;
}

/* 筛选表头样式 */
.header-filter {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 20px; /* 确保图标有最小宽度 */
}

/* 确保筛选图标可点击区域足够大 */
.header-filter i {
  padding: 4px;
  margin: -4px;
  cursor: pointer; /* 明确显示为可点击 */
}

/* 类型选项样式 */
.type-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 8px;
}

.type-option {
  padding: 6px 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.type-option:hover {
  background-color: #f0f0f0;
}

.type-option.selected {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: 500;
}
</style>    